<template>
  <view  class="container" @click="handleClickOutside">
    <messageHeader class="msg-navbar" ref="header" title="消息"></messageHeader>

    <view v-if="isLogin" class="">
    	<view class="tabs">
    	  <view class="tab-item" @click="go(1)">
    	    <text class="tab-icon">💬</text> <!-- 评论和回复图标 -->
    	    <text>评论和回复</text>
			<view class="notification-dot" v-if="commentsHasNew" ></view>
    	  </view>
    	  <view class="tab-item" @click="go(2)">
    	    <text class="tab-icon">❤️</text> <!-- 赞和收藏图标 -->
    	    <text>赞和收藏</text>
			<view class="notification-dot" v-if="LikesHasNew" ></view>
    	  </view>
    	  <view class="tab-item" @click="go(3)">
    	    <text class="tab-icon">👥</text> <!-- 新增粉丝图标 -->
    	    <text>新增粉丝</text>
			<view class="notification-dot" v-if="fansHasNew"></view>
    	  </view>
    	</view>
    	<scroll-view class="message-list" scroll-y :style="{ height: addressBookHeight }">
    		<view class="null" v-if="messages.length==0">
    			您还没有任何聊天消息
    		</view>
    	  <view 
    	    class="message-item" 
    	    v-for="(message, index) in messages" 
			v-if="(message.toUid==uid)||(String(uid)==message.toUid)"
    	    :key="index"
    	    :class="{ 'top-message': message.isTop, 'deleting': message.isDeleting }"
    	    @touchstart="touchStart($event, index)"
    	    @touchmove="touchMove($event, index)"
    	    @touchend="touchEnd(index)"
    	    :style="{ transform: `translateX(${message.offsetX}rpx)` }"
    	    @click.stop="onMessageClick"
    	  >
		  	<u-avatar :src="message.avatar" class="avatar" @click="goToPersonalInformation(message.uid,message.username)" />
		  	<view class="message-info"  @click="goToChat(index, message.uid, message.username)">
		  	  <view class="message-header">
		  	    <text class="message-title">{{ message.username }}</text>
		  	    <text class="message-time">{{ timeShow(message.time) }}</text>
		  	  </view>
		  	  <text class="message-content">{{ message.content }}</text>
		  	</view>
		  	
		  	<view class="notification-dot" v-if="message.hasNew"></view>
		  	    	
		  	<view class="action-buttons" :style="{ opacity: message.offsetX < -20 ? 1 : 0 }">
		  	  <view class="button top-button" @click="topMessage(index)">
		  	    {{ message.isTop ? '取消置顶' : '置顶' }}
		  	  </view>
		  	  <view class="button read-button" @click="markAsRead(index)">
		  	    {{ message.hasNew ? '已读' : '未读' }}
		  	  </view>
		  	  <view class="button delete-button" @click="deleteMessage(index)">删除</view>
		  	</view>
    	  </view>
    	</scroll-view>
    </view>
	<view v-else class="notLogin">
		<text class="unLogin">您当前还没有登录</text>
		  <view class="login-button" @click="navigateToLogin">去登录/注册</view>
		  <text class="unLogin">点击前往登录注册，登录后即可查看其他用户发来的私信</text>
	</view>

    <myTabBar class="myTabBar"></myTabBar>
  </view>
</template>
forEach
<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
	  isLogin:false,
	  uid:"",
	  token:"",
      defaultAvatar: '',
      addressBookHeight: 0,
	  commentsHasNew:false,
	  LikesHasNew:false,
	  fansHasNew:false,
      touch: { startX: 0 },
      messages: [
		  // {
		  //   uid: 1,
		  //   avatar: 'https://ts4.cn.mm.bing.net/th?id=OIP-C.mOQzyKsTXubxqVBZPY_i5gAAAA&w=250&h=250&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2',
		  //   username: '入坤东',
		  //   time: '昨天 8点',
		  //   content: '太谢谢你了！我必须送你我最爱的铜锣烧 太谢谢你了！我必须送你我最爱的铜锣烧 太谢谢你了！我必须送你我最爱的铜锣烧 太谢谢你了！我必须送你我最爱的铜锣烧',
		  //   offsetX: 0,
		  //   isTop: false,
		  //   hasNew: false,
		  //   isDeleting: false,
		  // },
		  // {
		  //   uid: 2,
		  //   avatar: '',
		  //   username: '大帅鱼',
		  //   time: '3天前',
		  //   content: '小平哥，能教我怎么写作业吗？',
		  //   offsetX: 0,
		  //   isTop: false,
		  //   hasNew: false,
		  //   isDeleting: false,
		  // },
	  ],
    };
  },
  computed: {
  	    ...mapState(["isUsersListChange","isCommentsChange","isLikesChange",'isFansChange']), // 映射 Vuex 状态
  	 },
  watch:{
	isUsersListChange(newVal,oldVal) {
		this.messages=uni.getStorageSync('usersList');
		this.messages.forEach((message)=>{
			message.avatar=uni.getStorageSync('userAvatar'+message.uid);
		})
	 },
	 isCommentsChange(newVal, oldVal) {
		 console.log(newVal)
	 	if(newVal!=null){
			this.commentsHasNew=true
			uni.setStorageSync('commnetsHasNew',true)
		}
	 },
	 isLikesChange(newVal, oldVal) {
		 if(newVal!=null){
			this.LikesHasNew=true
			uni.setStorageSync('likesHasNew',true)
		 }
	 },
	 isFansChange(newVal, oldVal) {
		 if(newVal!=null){
			this.fansHasNew=true
			uni.setStorageSync('fansHasNew',true)
		 }
	 }
  },
  onLoad() {
	  this.getAddressBookHeight();
	  var uid=uni.getStorageSync('UID')||null
	  this.token=uni.getStorageSync("token")
	  var usersList=uni.getStorageSync('usersList');
	  this.commentsHasNew=uni.getStorageSync('commnetsHasNew')||false
	  this.LikesHasNew=uni.getStorageSync('likesHasNew')||false
	  this.fansHasNew=uni.getStorageSync('fansHasNew')||false
	  this.uid=uid;
	  var token=uni.getStorageSync("token")||null
	  if(uid!=null&&token!=null){
	  	this.isLogin=true
	  }
	this.messages=uni.getStorageSync('usersList');
	if(this.messages.length>0)
	this.messages.forEach((message)=>{
		message.avatar=uni.getStorageSync('userAvatar'+message.uid);
	})
  },
  onShow() {

  },
  methods: {
	  timeShow(timestamp){
	  		 const now = new Date();
	  		    const messageTime = new Date(timestamp);
	  		    const diffInSeconds = Math.floor((now - messageTime) / 1000);
	  		    
	  		    if (diffInSeconds < 60) {
	  		        return '刚刚';
	  		    } else if (diffInSeconds < 3600) {
	  		        const minutes = Math.floor(diffInSeconds / 60);
	  		        return `${minutes}分钟前`;
	  		    } else if (diffInSeconds < 86400) {
	  		        const hours = Math.floor(diffInSeconds / 3600);
	  		        return `${hours}小时前`;
	  		    } else {
	  		        const year = messageTime.getFullYear();
	  		                const month = String(messageTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
	  		                const day = String(messageTime.getDate()).padStart(2, '0');
	  		                const hour = String(messageTime.getHours()).padStart(2, '0');
	  		                const minute = String(messageTime.getMinutes()).padStart(2, '0');
	  		                
	  		                return `${year}-${month}-${day} ${hour}:${minute}`;
	  		    }
	  },
	  getUserAvatar(uid){
		  var userAvatar=null
		  uni.request({
		      url: this.baseUrl+'/getUserAvatar',
		      method: 'POST',
		      data: {
		  		data:{
		  			userId:Number(uid)
		  		},
		  		msgType:'getUserAvatar'
		      },
		      header: {
		  		'Content-Type': 'application/json',
		  		'token':this.token,
		  		'uid':this.uid
		      },
		      success: (res) => {
		  		console.log(res);
		  		if(res.data.code==1){
		  			 userAvatar=res.data.data.imgType+'base64,'+res.data.data.userAvatar;
					 return userAvatar
		  		}
		      },
		      fail: (err) => {
		  		console.error('请求失败:', err);
		      },
		  });
		  
	  },
    handleClickOutside() {
      this.resetMessages();
      this.$refs.header.togglePopup(false);
    },
    goToPersonalInformation(uid,username) {
      uni.navigateTo({
        url: "/pages/personalInformation/personalInformation?uid=" + uid+"&username="+username
      });
    },
    go(index) {
		if(index==1){
			this.commentsHasNew=false
			uni.setStorageSync('commnetsHasNew',false)
		}else if(index==2){
			this.LikesHasNew=false
			uni.setStorageSync('likesHasNew',false)
		}else{
			this.fansHasNew=false
			uni.setStorageSync('fansHasNew',false)
		}
      uni.navigateTo({
        url: "/pages/conmmentLikeFuns/conmmentLikeFuns?index=" + index
      });
    },
    goToChat(index, uid, username) {
      this.$set(this.messages[index], 'hasNew', false);
	  var usersList=uni.getStorageSync('usersList')||[]
	  	var user = usersList.find(existingUser => existingUser.uid == uid);
	  	user.hasNew=false
		uni.setStorageSync('usersList',usersList);
		// this.$store.commit('changeUsersList',usersList)	 //不用这个全局通知也没问题

      uni.navigateTo({
        url: "/pages/chat/chat?uid=" + uid + "&username=" + username
      });
    },
    getAddressBookHeight() {
      uni.getSystemInfo({
        success: (systemInfo) => {
          const statusBarHeight = systemInfo.statusBarHeight;
          const totalHeight = systemInfo.windowHeight;
          const head = uni.upx2px(200);
          const navBarHeight = uni.upx2px(130);
          this.addressBookHeight = `${totalHeight - statusBarHeight - navBarHeight - head}px`;
        }
      });
    },
    touchStart(event, index) {
      this.resetMessages();
      this.touch.startX = event.touches[0].clientX;
    },
    touchMove(event, index) {
      const deltaX = event.touches[0].clientX - this.touch.startX;
      const rpxOffset = deltaX / uni.upx2px(1);
      this.$set(this.messages[index], 'offsetX', Math.min(0, Math.max(rpxOffset, -100)));
    },
    touchEnd(index) {
      const threshold = -50;
      if (this.messages[index].offsetX < threshold) {
        this.$set(this.messages[index], 'offsetX', -300);
      } else {
        this.$set(this.messages[index], 'offsetX', 0);
      }
    },
    resetMessages() {
	if(this.messages)
      this.messages.forEach((message) => {
        this.$set(message, 'offsetX', 0);
      });
    },
    onMessageClick() {
      this.resetMessages();
    },
    topMessage(index) {
      const messageToTop = this.messages[index];

      if (messageToTop.isTop) {
        this.messages.splice(index, 1);
        this.messages.push({ ...messageToTop, isTop: false });
        uni.showToast({ title: '取消置顶', icon: 'none', duration: 500 });
      } else {
        this.messages.splice(index, 1);
        this.messages.unshift({ ...messageToTop, isTop: true });
        uni.showToast({ title: '消息已置顶', icon: 'none', duration: 500 });
      }
    },
    deleteMessage(index) {
      this.$set(this.messages[index], 'isDeleting', true); // 设置删除状态
      // #ifdef APP
      plus.device.vibrate(100);
      // #endif
	  var usersList = uni.getStorageSync('usersList') || [];
	  var userIndex = usersList.findIndex(existingUser => existingUser.uid ==this.messages[index].uid);
	  if (userIndex !== -1) { 
	      // 将用户移到最前面
	      var user = usersList.splice(userIndex, 1)[0]; 
		  uni.setStorageSync('usersList',usersList)
		  this.$store.commit('changeUsersList',usersList)
	  }
      uni.showToast({ title: '消息已删除', icon: 'none', duration: 500 });

      setTimeout(() => {
        this.messages.splice(index, 1);
      }, 500); // 延迟删除消息
    },
    markAsRead(index) {
      const message = this.messages[index];
      if (message.hasNew) {
        this.$set(this.messages[index], 'hasNew', false);
        uni.showToast({ title: '消息已标记为已读', icon: 'none', duration: 500 });
      } else {
        this.$set(this.messages[index], 'hasNew', true);
        uni.showToast({ title: '消息已标记为未读', icon: 'none', duration: 500 });
      }
    },
	navigateToLogin() {
	      // 跳转到登录/注册页面
	      uni.navigateTo({
	        url: '/pages/login/login' // 替换为你的登录/注册页面路径
	      });
	    },
  },
};
</script>

<style scoped>
.container {
  padding-top: var(--status-bar-height);
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.notLogin{
	  margin-top: 600rpx;
	  display: flex;
	  flex-direction: column; /* 垂直排列 */
	  justify-content: center; /* 垂直居中 */
	  align-items: center; /* 水平居中 */
	  text-align: center; /* 文本居中对齐 */
}
@keyframes glow {
  0% {
    box-shadow: 0 0 10rpx rgba(0, 255, 255, 0.6), 0 0 20rpx rgba(255, 0, 255, 0.4);
    border-color: #00ffff;
  }
  25% {
    box-shadow: 5rpx 5rpx 15rpx rgba(0, 255, 255, 0.8), 5rpx 5rpx 30rpx rgba(255, 0, 255, 0.5);
    border-color: #ff00ff;
  }
  50% {
    box-shadow: 0 0 20rpx rgba(255, 0, 255, 0.6), 0 0 25rpx rgba(0, 255, 255, 0.4);
    border-color: #00ffff;
  }
  75% {
    box-shadow: -5rpx -5rpx 15rpx rgba(0, 255, 255, 0.8), -5rpx -5rpx 30rpx rgba(255, 0, 255, 0.5);
    border-color: #ff00ff;
  }
  100% {
    box-shadow: 0 0 10rpx rgba(0, 255, 255, 0.6), 0 0 20rpx rgba(255, 0, 255, 0.4);
    border-color: #00ffff;
  }
}
.login-button {
  padding: 20rpx 40rpx; /* 按钮内边距 */
  border-radius: 50%;
   animation: glow 2s infinite;
  background-color: #fbffe1;
  margin: 20rpx 200rpx 0 200rpx;
  color: #ff6a00; /* 按钮文字颜色 */
  border: none; /* 去掉边框 */
  border-radius: 20rpx; /* 圆角 */
  font-size: 35rpx; /* 字体大小 */
}
.unLogin{
	color: gainsboro;
	text-align: center;
	margin: 20rpx 100rpx 0 100rpx;
}
.msg-navbar {
  height: 50rpx;
}
.tabs {
  display: flex;
  background-color: #f9f9f9;
  padding: 20rpx 0; 
  border-bottom: 1rpx solid #eee;
  height: 120rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  position: relative;
  padding: 10rpx 0; /* 调整为10rpx以适应图标和文字 */
  margin: 0 20rpx; /* 调整间距 */
  font-size: 30rpx;
  color: #333;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
}

.tab-icon {
  font-size: 40rpx; /* 图标大小 */
  display: block; /* 使图标单独占一行 */
  margin-bottom: 10rpx; /* 图标与文字之间的间距 */
}

.message-list {
  overflow-y: auto;
  padding: 20rpx 0 0 0;
  background-color: #fff;
}
.myTabBar {
  height: 130rpx;
}
.message-item {
  position: relative;
  display: flex;
  padding: 30rpx;
  margin: 0 20rpx 20rpx 20rpx;
  border-radius: 10rpx;
  box-shadow: 1rpx 3rpx 2rpx 5rpx rgba(0, 0, 0, 0.1);
  background-color: #fdfdfd;
  transition: transform 0.3s;
}
.top-message {
  background-color: #d3d3d3;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 25rpx;
  margin-right: 20rpx;
  border-radius: 50%;
  border: 6rpx solid #dddddd;
}

.message-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.message-header {
  display: flex;
  justify-content: space-between;
}

.message-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.message-content {
  width: 80%;
  display: -webkit-box;
  font-size: 26rpx;
  color: #666;
  margin-top: 10rpx;
  white-space: normal; 
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;    
}

.action-buttons {
  position: absolute;
  top: 0;
  bottom: 0;
  right: -300rpx;
  width: 300rpx;
  display: flex;
  transition: opacity 0.3s;
}

.button {
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  color: white;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
  font-size: 25rpx;
  margin: 0;
  transition: background-color 0.3s, transform 0.2s;
  text-align: center;
}

.read-button {
  width: 100rpx;
  background-color: #FFA500;
}

.top-button {
  width: 100rpx;
  background-color: #007bff;
}

.delete-button {
  width: 100rpx;
  background-color: #dc3545;
}

.notification-dot {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 20rpx;
  height: 20rpx;
  background-color: red;
  border-radius: 50%;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.message-item.deleting {
  animation: fadeOut 1s forwards; /* 应用渐变消失动画 */
}
.null{
	color: lightgray;
	font-size: 30rpx;
	text-align: center;
}
</style>
